<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

function makeSalt($str){
	return md5($str.'#$#$%#$#%#ftgftCVFG!!!!!'.$str.'__))((__');
}

function isLogin(){
	$ci = &get_instance();
	$ci->db->set_dbprefix(SITE_REF.'_');
	return $ci->session->userdata('account') ? true: false;
}

function getAccountUserId(){
	$ci = &get_instance();
	$ci->db->set_dbprefix(SITE_REF.'_');
	
	if(isLogin()){
		$session_array = $ci->session->userdata('account');
		return $session_array['user_id'];
	}
	return false;
}

function getAccountUserObject($dynamic=false){
	$ci = &get_instance();
	$ci->db->set_dbprefix(SITE_REF.'_');
	
	if(isLogin()){
		if(!$dynamic){
			$session_array = $ci->session->userdata('account');
			return $session_array['user_obj'];
		}else{
			return $ci->user_entity->init('id',getAccountUserId());
		}
		//
	}
	return false;
}

function getPermission(){
	$ci = &get_instance();
	$ci->db->set_dbprefix(SITE_REF.'_');
	
	if(isLogin()){
		$session_array = $ci->session->userdata('account');
		return $session_array['user_obj']->getPermissionSlug();
	}
	return false;
}

function newCaptcha(){
	$ci = &get_instance();
	$ci->db->set_dbprefix(SITE_REF.'_');
	
	$ci->load->helper('captcha');	
	$timeLIMIT = 72000;
	$captchaContent = $ci->digit->rand_string(5);
	$content = strtolower($captchaContent);
	$captcha = array( 'captcha_exprise_time'=>time() + $timeLIMIT , 'captcha_content'=>$content );
	$ci->session->set_userdata($captcha);	
	$vals = array(
		'word' => $captchaContent,
		'img_path' => './captcha/images/',
		'img_url' => site_url().'captcha/images/',
		'font_path' => './captcha/fonts/arial.ttf',
		'img_width' => '130',
		'img_height' => '30',
		'expiration' => $timeLIMIT
		);
	$cap = create_captcha($vals);
	return $cap['image'];
}

function currencyDisplay($amount){
	$number = sprintf('%.2f', $amount); 
    while (true) { 
        $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number); 
        if ($replaced != $number) { 
            $number = $replaced; 
        } else { 
            break; 
        } 
    } 
    return $number; 
}

function format($number){
	return number_format($number,2);
}

function euroCurrencyFormat($string){
    //replace .=>, and ,=>.
    $strTemp = str_replace(array(',','.'), array('$1','$2'), $string);
    $currency = str_replace( array('$1','$2'), array('.',','), $strTemp);
    return $currency;
}

function breadcumb($pos=1, $dataArray=array()){
	if(!isset($_SESSION['sys_breadcumb'])){
		$_SESSION['sys_breadcumb'][1] = array( language_translate('breadcumb_home') , site_url_lang('home') );
	}
	$_SESSION['sys_breadcumb'][$pos]	=	$dataArray;
}

function breadcumb_reset(){
	unset($_SESSION['sys_breadcumb']);
	$_SESSION['sys_breadcumb'][1] = array( language_translate('breadcumb_home') , site_url_lang('home') );
}

function getCountryInfoFromUserGeoLocation(){
	include_once('ip2locationlite.class.php');
 
	//Set geolocation cookie
	if(!isset($_COOKIE["geolocation_highescort"])){
	  $ipLite = new ip2location_lite;
	  $ipLite->setKey('06fc082707b16fc07af8082fdeceed43569eece7ad373b60b82a8870b0f555c6');
	 
	  $visitorGeolocation = $ipLite->getCountry($_SERVER['REMOTE_ADDR']);
	  if ($visitorGeolocation['statusCode'] == 'OK') {
		$data = base64_encode(serialize($visitorGeolocation));
		setcookie("geolocation_highescort", $data, time()+3600*24*7); //set cookie for 1 week
	  }
	}else{
	  $visitorGeolocation = unserialize(base64_decode($_COOKIE["geolocation_highescort"]));
	}
	
	$ci = &get_instance();
	$country = $ci->countries_entity->init('code',$visitorGeolocation['countryCode']);
	return $country ? $country:false;
	//array(5) { ["statusCode"]=> string(2) "OK" ["statusMessage"]=> string(0) "" ["ipAddress"]=> string(14) "113.190.88.196" ["countryCode"]=> string(2) "VN" ["countryName"]=> string(8) "VIET NAM" }
}

function getCityInfoFromUserGeoLocation(){
	include_once('ip2locationlite.class.php');
	$ci = &get_instance();
	
	//Set geolocation cookie
	if(!isset($_COOKIE["geolocation_highescort_city"])){
	  $ipLite = new ip2location_lite;
	  $ipLite->setKey('06fc082707b16fc07af8082fdeceed43569eece7ad373b60b82a8870b0f555c6');
	 
	  $visitorGeolocation = $ipLite->getCity($_SERVER['REMOTE_ADDR']);
	  if ($visitorGeolocation['statusCode'] == 'OK') {
		$data = base64_encode(serialize($visitorGeolocation));
		setcookie("geolocation_highescort_city", $data, time()+3600*24*7); //set cookie for 1 week
	  }
	}else{
	  $visitorGeolocation = unserialize(base64_decode($_COOKIE["geolocation_highescort_city"]));
	}
	
	$current_dbprefix = $ci->db->dbprefix;
	$ci->db->set_dbprefix('default_');
	
	$country = $ci->countries_entity->init('code',$visitorGeolocation['countryCode']);
	
	$return_array = array('state_id'=>0,'city_id'=>0);
	
	if(isset($visitorGeolocation)){
		if($visitorGeolocation['countryCode'] == 'ES'){
			$state = $ci->db->query("SELECT * FROM ".TBL_SPAIN_STATE." WHERE UPPER(region_name_spanish) LIKE '%".strtoupper($visitorGeolocation['regionName'])."%'")->result();
			if($state){
				$city = $ci->db->
					query("SELECT A.* FROM ".TBL_SPAIN_CITY." AS A INNER JOIN ".TBL_SPAIN_PROVINCE." AS B ON A.province_code = B.province_code	 WHERE REPLACE( UPPER(A.city_name_spanish), ' ', '' ) LIKE '%".strtoupper($visitorGeolocation['cityName'])."%' AND B.region_code = '".$state[0]->state_code."'")
					->result();
			}
		}else{
			$state = $ci->db->query("SELECT * FROM ".TBL_STATE." WHERE UPPER(state_name) LIKE '%".strtoupper($visitorGeolocation['regionName'])."%' AND country_code = '".$visitorGeolocation['countryCode']."'")->result();
			if($state){
				$city = $ci->db->
					query("SELECT * FROM ".TBL_CITY." WHERE REPLACE( UPPER(city_name),' ','' ) LIKE '%".strtoupper($visitorGeolocation['cityName']).
								"%' AND country_code = '".$visitorGeolocation['countryCode']."' AND state_code = '".$state[0]->state_code."'")
					->result();
			}
		}
		
		if(isset($state) AND !empty($state)){
			$return_array['state_id'] = $state[0]->id;
		}
		if(isset($city) AND !empty($city)){
			$return_array['city_id'] = $city[0]->id;
		}
		$return_array['city_name'] = $visitorGeolocation['cityName'];
		$return_array['region_name'] = $visitorGeolocation['regionName'];
	}
	$ci->db->set_dbprefix($current_dbprefix);
	
	return $return_array;
	//Array ( [statusCode] => OK [statusMessage] => [ipAddress] => 123.16.171.185 [countryCode] => VN [countryName] => VIET NAM [regionName] => HA NOI [cityName] => HANOI [zipCode] => - [latitude] => 21.033 [longitude] => 105.85 [timeZone] => +07:00 ) 
}





